package com.xy.utils;

import org.apache.poi.xwpf.usermodel.*;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class DocHandlerUtil {

    // 动态值映射（前缀 → 目标值）
    private static final Map<String, String> VALUE_MAP = new HashMap<>();
    static {
        VALUE_MAP.put("ygname", "李四");
        VALUE_MAP.put("age", "25");
        VALUE_MAP.put("dex", "75");
        VALUE_MAP.put("ygbirthday", "60kg");
    }

    // 记录已处理的前缀（确保唯一性）
    private static final Map<String, Boolean> processedPrefixes = new HashMap<>();

//    public static void main(String[] args) {
//        try (FileInputStream fis = new FileInputStream("/pics/pleadings.docx");
//             XWPFDocument doc = new XWPFDocument(fis)) {
//
//            Map<String, String> labelMap = new HashMap<>();
//            for (String label : docLabel) {
//                labelMap.put(label, "");
//            }
//            processDocument(doc, labelMap); // 处理文档
//
//            // 保存结果
//            try (FileOutputStream fos = new FileOutputStream("output.docx")) {
//                doc.write(fos);
//            }
//            System.out.println("替换完成！");
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        try {
//            Map<String,String> labelMap = getAllLabel(new XWPFDocument(new FileInputStream("/pics/pleadings.docx")), DocxTypeAndLabelEnum.getDocxKeyStringsByType(1));
//            labelMap.forEach((key, value) -> System.out.println(key + ": " + value));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 获取所有的标签值
     * @param doc
     * @return
     */
    public static Map<String,String> getAllLabel(XWPFDocument doc,String[] labels) {
        Map<String,String> labelMap = new HashMap<>();
        for (String label : labels) {
            labelMap.put(label, "");
        }
        // 初始化已处理前缀记录
        processedPrefixes.clear();
        // 处理所有段落、表格、页眉页脚
        doc.getParagraphs().forEach(para -> processParagraphGetAllLabel(para, labelMap));
        doc.getTables().forEach(table ->
                table.getRows().forEach(row ->
                        row.getTableCells().forEach(cell ->
                                cell.getParagraphs().forEach(para -> processParagraphGetAllLabel(para, labelMap))
                        )
                )
        );
        /**页眉页脚可能不需要
        doc.getHeaderList().forEach(header ->
                header.getParagraphs().forEach(para -> processParagraphGetAllLabel(para, labelMap))
        );
        doc.getFooterList().forEach(footer ->
                footer.getParagraphs().forEach(para -> processParagraphGetAllLabel(para, labelMap))
        );*/
        return labelMap;
    }

    /**
     * 匹配每段文本中的占位符并填充到labelMap中
     * @param para 段落
     * @param labelMap 标签值映射
     */
    public static void processParagraphGetAllLabel(XWPFParagraph para, Map<String,String> labelMap) {
        String fullText = para.getText();
        if (fullText == null || !fullText.contains("[")) return;
        // 正则匹配占位符（格式：前缀[...]）
        String prefixLabels = labelMap.keySet().stream().collect(Collectors.joining("|"));
        Pattern pattern = Pattern.compile("\\b("+ prefixLabels + ")\\[.*?\\]");
        Pattern patternContent = Pattern.compile("\\[(.*?)\\]");
        Matcher matcher = pattern.matcher(fullText);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String prefix = matcher.group(1); // 提取前缀
            Matcher matcherContent = patternContent.matcher(matcher.group());
            if (matcherContent.find()) {
                String content = matcherContent.group(1);
                labelMap.put(prefix, content);
            }
        }
    }
    /**
     * 替换文档中的占位符为输入值
     */
    public static void writeDocContent(XWPFDocument doc, Map<String,String> labelMap) {
        // 初始化已处理前缀记录
        processedPrefixes.clear();

        // 处理所有段落、表格、页眉页脚
        doc.getParagraphs().forEach(para -> processParagraph(para, labelMap));
        doc.getTables().forEach(table ->
                table.getRows().forEach(row ->
                        row.getTableCells().forEach(cell ->
                                cell.getParagraphs().forEach(para -> processParagraph(para, labelMap))
                        )
                )
        );

    }


    /**
     * 处理单个段落
     */
    private static void processParagraph(XWPFParagraph para, Map<String,String> labelMap) {
        String fullText = para.getText();
        if (fullText == null || !fullText.contains("[")) return;

        // 正则匹配占位符（格式：前缀[...]）
        String prefixLabels = labelMap.keySet().stream().collect(Collectors.joining("|"));
        Pattern pattern = Pattern.compile("\\b("+ prefixLabels + ")\\[.*?\\]");
        Matcher matcher = pattern.matcher(fullText);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String prefix = matcher.group(1); // 提取前缀
            // 替换为动态值并标记为已处理
            String value = labelMap.getOrDefault(prefix, "N/A");
            matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
            processedPrefixes.put(prefix, true);
        }
        matcher.appendTail(sb);
        // 更新段落文本
        updateParagraph(para, sb.toString());
    }



    /**
     * 更新段落内容（保留格式）
     */
    private static void updateParagraph(XWPFParagraph para, String newText) {
        para.getRuns().forEach(run -> run.setText("", 0));
        XWPFRun newRun = para.createRun();
        newRun.setText(newText);

        // 保留第一个Run的格式（可选）
        if (!para.getRuns().isEmpty()) {
            XWPFRun sampleRun = para.getRuns().get(0);
            newRun.setFontFamily(sampleRun.getFontFamily());
            newRun.setFontSize(sampleRun.getFontSize());
        }
    }





}
